package com.ncmmall.api.utils;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

/**
 * 微信解密工具
 *
 * @author linxs
 * @date 2019-07-24 17:27
 */
@Slf4j
public class WXBizDataCrypt {

    private final String sessionKey;

    public WXBizDataCrypt(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     *
     * @param encryptedData string 加密的用户数据
     * @param iv            string 与用户数据一同返回的初始向量
     * @return data string 解密后的原文
     */
    public JSONObject decryptData(String encryptedData, String iv) {

        Base64.Decoder decoder = Base64.getMimeDecoder();
        byte[] dataByte = decoder.decode(encryptedData);
        byte[] keyByte = decoder.decode(sessionKey);
        byte[] ivByte = decoder.decode(iv);

        try {
            // 如果密钥不足16位，那么就补足
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                keyByte = Arrays.copyOf(keyByte, groups * base);
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.fromObject(result);
            }
            throw new IllegalArgumentException("解密内容为空");
        } catch (Exception e) {
            log.error("[微信数据解密异常]", e);
            throw new IllegalArgumentException("解密异常");
        }
    }

}
